// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import wx from "weixin-js-sdk";
import "./core/PIXI.extends.js";
import App from "./App";

import TWEEN, {
	L_ANI_TIME,
	B_ANI_TIME,
	M_ANI_TIME,
	S_ANI_TIME,
	Tween
} from "./core/Tween";

const _Promise = window.Promise;
window.Promise = function Promise(...args) {
	const res_promise = new _Promise(...args);
	res_promise.catch(function(err) {
		Raven.captureException((err && err.stack) || String(err), {
			level: "error",
			logger: "Promise",
			curent_stage: window.__CURENT_STAGE__
		});
	});
	return res_promise;
};
["resolve", "reject", "all", "race"].forEach(function(key) {
	Promise[key] = _Promise[key];
});
window.addEventListener("error", err => {
	if (err instanceof window.ErrorEvent) {
		err = err.error;
	}
	Raven.captureException((err && err.stack) || String(err), {
		level: "error",
		logger: "window.onerror",
		curent_stage: window.__CURENT_STAGE__
	});
});
window.addEventListener("unhandledrejection", err => {
	Raven.captureException((err && err.stack) || String(err), {
		level: "error",
		logger: "window.unhandledrejection",
		curent_stage: window.__CURENT_STAGE__
	});
});
Vue.config.errorHandler = function(err, vm) {
	Raven.captureException((err && err.stack) || String(err), {
		level: "error",
		logger: "Vue.config.errorHandler",
		curent_stage: window.__CURENT_STAGE__,
		tags: { vm_name: vm ? vm.name : "???" }
	});
};

// 省电模式
// window.requestAnimationFrame = (()=>{
//   const raf = window.requestAnimationFrame;
//   return function (cb) {
//     return raf(()=>raf(()=>cb()));
//   }
// })();
const queryString = (window.queryString = {
	parse(query_string = location.search) {
		if (query_string.indexOf("?") === 0) {
			query_string = query_string.substr(1);
		}
		const query = {};
		query_string.split("&").forEach(query_str => {
			const query_info = query_str.split("=");
			if (query_info[0]) {
				query[decodeURIComponent(query_info[0])] = decodeURIComponent(
					query_info[1]
				);
			}
		});
		return query;
	},
	stringify(query) {
		const res = [];
		for (let key in query) {
			const val = query[key];
			if (val) {
				res.push(
					encodeURIComponent(key) + "=" + encodeURIComponent(val)
				);
			}
		}
		return res.join("&");
	}
});
const query = (window.query = queryString.parse());

window.is_weixin =
	navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
	"micromessenger";
window.wx = wx;
window.wx_promise = new Promise((resolve, reject) => {
	if (!is_weixin) {
		// reject("不在微信中");
		resolve(wx);
		return;
	}

	fetch(
		`http://wx.youdob.org/get_js_config.php?domain=${encodeURIComponent("13shui.youdob.org")}&referer=${encodeURIComponent(location.host)}&url=${encodeURIComponent(location.href)}`
	)
		.then(res => res.json())
		.then(res => {
			const wx_config = res.obj;
			wx.config({
				debug: false,
				appId: wx_config.appId,
				timestamp: wx_config.timestamp,
				nonceStr: wx_config.nonceStr,
				signature: wx_config.signature,
				jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline"]
			});
			wx.ready(function(res) {
				window.wx = wx;
				console.log("微信配置完成", wx_config);
				resolve(wx);
			});
			wx.error(function(err) {
				reject(err);
			});
		});
});

window.base_href = (() => {
	var bases = document.getElementsByTagName("base");
	var baseHref = null;

	if (bases.length > 0) {
		baseHref = bases[0].href;
	} else {
		baseHref = `http://${location.host}/`;
	}
	return baseHref;
})();
if (location.hostname.indexOf("youdob") !== -1) {
	window.server_href = `http://120.25.238.30:3000`;
	window.server_host_href = `http://13shui-server.youdob.org`;
} else {
	window.server_host_href = window.server_href =
		window.__server_href__ || `http://${location.hostname}:3000`;
}

if (
	location.hostname.indexOf("youdob") !== -1 ||
	query.use_cdn ||
	window.__use_cdn__
) {
	window.resource_href = window.__resource_href__;
} else {
	window.resource_href = `http://${location.hostname}:8081/`;
}

const share_code = query.share_code || "";
window.wxLoginGetUserInfo = () => {
	if (is_weixin) {
		// 微信中强制跳转到微信登录页面
		// 当前的页面链接
		const cur_url = location.href;
		// 由游戏服务器跳转到当前页面
		const cb_url = `${server_host_href}/wx-code-cb?redirect_uri=${encodeURIComponent(cur_url)}&share_code=${encodeURIComponent(share_code)}`;
		// 由微信配置的代理服务器接收code并转发到游戏服务器
		const wx_login_url = `http://wx.youdob.org/get_user_info.php?cb_url=${encodeURIComponent(cb_url)}`;
		// 微信获取code的链接
		location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1d693905e74d09e8&redirect_uri=${encodeURIComponent(wx_login_url)}&response_type=code&scope=snsapi_userinfo&state=13shui#wechat_redirect`;
	}
};

Vue.config.productionTip = false;

/* 加载背景音乐并播放 */
// const bgMusic = window.bgm = new Howl({
//   // src: [resource_href + "sound/BEIJING.mp3", resource_href + "sound/BEIJING.ogg"],
//   src: ["./static/BEIJING.mp3", "./static/BEIJING.ogg"],
//   html5: true,
//   loop: true,
// });

/* eslint-disable no-new */
new Vue({
	el: "#app",
	template: "<App/>",
	components: {
		App
	}
});
